﻿using System;
using System.Globalization;
using System.Web.Mvc;
using Complaint.Common;
using Complaint.Models.Services;

namespace Complaint.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewData["Message"] = "Welcome to iComplain!";

            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        public ActionResult TNC()
        {
            return View();
        }

        public ActionResult Contact()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Contact(FormCollection collection)
        {
            var code = collection["CaptchaCode"];
            if (String.IsNullOrEmpty(code)
                || !String.Equals(code, Session["CAPTCHA_CODE"].ToString(), StringComparison.CurrentCulture))
            {
                ModelState.AddModelError("CaptchaCode", "Verification code does not match.");
                // if Builtin Model Binding is not used, for every ModelError added, a ModelValue is also needed 
                if (ModelState["CaptchaCode"].Value == null)
                {
                    ModelState["CaptchaCode"].Value =
                        new ValueProviderResult(
                            code,
                            code,
                            CultureInfo.CurrentCulture);
                }
                Response.StatusCode = 500;
                return View();
            }

            var subject = string.Format(
                            "{0}; Name: {1}; Email: {2}",
                            collection["subject"],
                            collection["name"],
                            collection["email"]);
            new MailService().Send(
                ConfigHelper.GetConfigValue("CommentReporter"),
                ConfigHelper.GetConfigValue("CommentModerator"),
                subject,
                collection["comment"]
                );
            return View("CommentReceived");
        }
    }
}
